package org.nci.platform.workflow.controller;


import gh.priv.general.common.vo.PageResult;
import gh.priv.general.common.vo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.nci.platform.workflow.dto.FlowProcDefDto;
import org.nci.platform.workflow.dto.FlowProcDefPageQuery;
import org.nci.platform.workflow.dto.FlowSaveXmlDto;
import org.nci.platform.workflow.service.IFlowDefinitionService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * <p>
 * 工作流程定义
 * </p>
 *
 * @author Tony
 * @date 2021-04-03
 */
@Slf4j
@Tag(name = "流程定义")
@RestController
@RequestMapping("/flowable/definition")
public class FlowDefinitionController{

    @Resource
    private IFlowDefinitionService flowDefinitionService;

    @PostMapping(value = "/page")
    @Operation(summary = "流程定义列表")
    public Result<PageResult<FlowProcDefDto>> page(@RequestBody FlowProcDefPageQuery query) {
        return Result.success(flowDefinitionService.page(query));
    }


    @Operation(summary = "导入流程文件", description = "上传bpmn20的xml文件")
    @PostMapping("/import")
    public Result<Boolean> importFile(@RequestParam(required = false) String name,
                                 @RequestParam(required = false) String category,
                                 MultipartFile file) {
        InputStream in = null;
        try {
            in = file.getInputStream();
            flowDefinitionService.importFile(name, category, in);
        } catch (Exception e) {
            log.error("导入失败:", e);
            return Result.error(e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("关闭输入流出错", e);
            }
        }

        return Result.success();
    }


    @Operation(summary = "读取xml文件")
    @GetMapping("/readXml/{deployId}")
    public Result<String> readXml(@Parameter(description = "流程定义id") @PathVariable(value = "deployId") String deployId) {
        try {
            return Result.success(flowDefinitionService.readXml(deployId));
        } catch (Exception e) {
            return Result.error("加载xml文件异常");
        }

    }

    @Operation(summary = "读取图片文件")
    @GetMapping("/readImage/{deployId}")
    public void readImage(@Parameter(description = "流程定义id") @PathVariable(value = "deployId") String deployId, HttpServletResponse response) {
        OutputStream os = null;
        BufferedImage image = null;
        try {
            image = ImageIO.read(flowDefinitionService.readImage(deployId));
            response.setContentType("image/png");
            os = response.getOutputStream();
            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    @Operation(summary = "保存流程设计器内的xml文件")
    
    @PostMapping("/save")
    public Result<Boolean> save(@RequestBody FlowSaveXmlDto vo) {
        InputStream in = null;
        try {
            in = new ByteArrayInputStream(vo.getXml().getBytes(StandardCharsets.UTF_8));
            flowDefinitionService.importFile(vo.getName(), vo.getCategory(), in);
        } catch (Exception e) {
            log.error("导入失败:", e);
            return Result.error(e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("关闭输入流出错", e);
            }
        }

        return Result.success();
    }

    @Operation(summary = "发起流程")
    @PostMapping("/start/{procDefId}/{currUserId}")
    public Result<Boolean> start(    @Parameter(description = "流程定义id")
                            @PathVariable(value = "procDefId") String procDefId,
                            @Parameter(description = "用户ID")
                            @PathVariable(value = "currUserId") String currUserId,
                            @Parameter(description = "变量集合,json对象")
                            @RequestBody Map<String, Object> variables) {
        flowDefinitionService.startProcessInstanceById(procDefId,currUserId, variables);
        return Result.success();
    }

    @Operation(summary = "激活或挂起流程定义")
    
    @PutMapping(value = "/updateState")
    public Result<Boolean> updateState(@Parameter(description = "1:激活,2:挂起", required = true) @RequestParam Integer state,
                                  @Parameter(description = "流程部署ID", required = true) @RequestParam String deployId) {
        flowDefinitionService.updateState(state, deployId);
        return Result.success();
    }

    @Operation(summary = "删除流程")
    
    @DeleteMapping(value = "/{deployIds}")
    public Result<Boolean> delete(@PathVariable String[] deployIds) {
        for (String deployId : deployIds) {
            flowDefinitionService.delete(deployId);
        }
        return Result.success();
    }

}
